package com.ccteam.fluidmusic.ui.playlist

import androidx.lifecycle.*
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.domain.playlistsheet.PlaylistSheetListDataUseCase
import com.ccteam.shared.domain.playlistsheet.PlaylistSheetListUserDataUseCase
import com.ccteam.shared.result.playlistsheet.PlaylistSheetListItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/15
 *
 * 歌单列表显示ViewModel
 * 该ViewModel两用，如果未传来userId值则显示公用的歌单列表
 * 否则显示用户自己的歌单列表
 */
@HiltViewModel
class PlaylistSheetListViewModel @Inject constructor(
    userCore: UserCore,
    savedStateHandle: SavedStateHandle,
    private val playlistSheetListUserDataUseCase: PlaylistSheetListUserDataUseCase,
    private val playlistSheetListDataUseCase: PlaylistSheetListDataUseCase
): ViewModel() {

    private val _showAddPlaylistButton = MutableLiveData(false)
    val showAddPlaylistButton: LiveData<Boolean> get() = _showAddPlaylistButton

    /**
     * 如果传来了userId，代表查询用户的歌单，需要调用另外的Domain层
     */
    val playlistSheetList: Flow<PagingData<PlaylistSheetListItem>> = (savedStateHandle.get<String>("userId"))?.let{ userId ->
        playlistSheetListUserDataUseCase(userId)
            .cachedIn(viewModelScope)
    } ?: run {
        playlistSheetListDataUseCase(null)
            .cachedIn(viewModelScope)
    }

    init {
        val userId = savedStateHandle.get<String>("userId")
        if(userId == userCore.userInfo.value.userId){
            _showAddPlaylistButton.value = true
        }
    }

}